﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Data.OleDb;
using System.Data;
using System.ComponentModel;

namespace AttentenceCheckSystem
{
    /// <summary>
    /// Interaction logic for QueryWindow.xaml
    /// </summary>
    public partial class QueryWindow : Window
    {
        class DaysInfo : Dictionary<DateTime, bool>
        {
        }

        public QueryWindow()
        {
            InitializeComponent();
            MonthPicker.SelectedDate = DateTime.Now.Date;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                DateTime day = Convert.ToDateTime(MonthPicker.SelectedDate);
                // 节假日查询与生成
                DaysInfo daysInfo = GenDaysInfo(day);
                // 生成报告
                GenQueryReport(day, daysInfo);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private DaysInfo GenDaysInfo(DateTime day)
        {
            DateTime startDate = common.GetCheckStartDate(day);
            DateTime endDate = common.GetCheckEndDate(day);
            DaysInfo result = new DaysInfo();
            for (DateTime curDate = startDate; curDate != endDate; curDate = curDate.AddDays(1))
                result[curDate] = false;

            string strConn = Properties.Settings.Default.Database1ConnectionString;

            using (System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(strConn))
            {
                conn.Open();
                System.Data.OleDb.OleDbCommand command = conn.CreateCommand();
                command.CommandText = "SELECT Date FROM daysinfo WHERE Date BETWEEN @start AND @end";
                command.Parameters.Add("@start", OleDbType.Date).Value = startDate;
                command.Parameters.Add("@end", OleDbType.Date).Value = endDate;
                OleDbDataReader reader = command.ExecuteReader();
                if (reader.HasRows)
                {
                    while (reader.Read())
                        result[Convert.ToDateTime(reader["Date"])] = true;
                }
                else
                {
                    for (DateTime curDate = startDate; curDate != endDate; curDate = curDate.AddDays(1))
                    {
                        if (curDate.DayOfWeek == DayOfWeek.Sunday || curDate.DayOfWeek == DayOfWeek.Saturday)
                            result[curDate] = true;
                    }
                }
            }

            return result;
        }

        private void GenQueryReport(DateTime day, DaysInfo daysInfo)
        {
            TabContainer.Items.Clear();
            DateTime startDate = common.GetCheckStartDate(day);
            DateTime endDate = common.GetCheckEndDate(day);
            string strConn = Properties.Settings.Default.Database1ConnectionString;
            using (System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(strConn))
            {
                // 先从数据库读取数据
                conn.Open();
                DataSet dataSet = new DataSet();

                string strCommand = "SELECT * FROM [user];";
                OleDbDataAdapter userAdapter = new OleDbDataAdapter(strCommand, conn);
                OleDbCommandBuilder mybuilder = new OleDbCommandBuilder(userAdapter);

                int i = userAdapter.Fill(dataSet, "user");

                OleDbCommand command = new OleDbCommand("SELECT * FROM 打卡记录 WHERE 日期 BETWEEN @startDate AND @endDate ORDER BY 日期", conn);
                command.Parameters.Add("@startDate", OleDbType.Date).Value = startDate.AddDays(-1);
                command.Parameters.Add("@endDate", OleDbType.Date).Value = endDate;
                OleDbDataAdapter recordAdapter = new OleDbDataAdapter(command);
                i = recordAdapter.Fill(dataSet, "打卡记录");

                PlayerManager userManager = new PlayerManager();

                DataTable userTable = dataSet.Tables["user"];
                DataTable recordTable = dataSet.Tables["打卡记录"];
                foreach (DataRow row in userTable.Rows)
                {
                    string userName = Convert.ToString(row["姓名"]);
                    int nID = Convert.ToInt32(row["ID"]);
                    PlayerRecord userRecord = userManager[userName];
                    
                    // 为每个人生成考勤周期
                    for (DateTime curDate = startDate; curDate != endDate; curDate = curDate.AddDays(1))
                        userRecord.Add(curDate).IsHoliday = daysInfo[curDate];
                    
                    // 根据请假情况生成规定上下班时间

                    // 填入考勤记录
                    foreach (DataRow recordRow in recordTable.Select("uid=" + nID.ToString()))
                    {
                        DateTime date = Convert.ToDateTime(recordRow["日期"]);
                        userRecord[date].AddRecord(Convert.ToDateTime(recordRow["记录1"]));
                        if (!(recordRow["记录2"] is DBNull))
                        {
                            userRecord[date].AddRecord(Convert.ToDateTime(recordRow["记录2"]));
                        }
                        if (userRecord[date].CheckOutTime.HasValue)
                        {
                            userRecord[date.AddDays(1)].CheckOutVeryLate(userRecord[date].CheckOutTime.Value);
                        }
                    }
                    
                    // 后续处理
                    userRecord.PostProcess(startDate.AddDays(-1));
                    // 生成报告
                    TabItem tabItem = new TabItem();
                    tabItem.Header = userName;
                    ReportCtrl ctrl = new ReportCtrl();
                    tabItem.Content = ctrl;
                    tabItem.DataContext = userRecord; 
                    TabContainer.Items.Add(tabItem);

                    ICollectionView view = CollectionViewSource.GetDefaultView(userRecord.items);
                    if (view.Filter == null)
                    {
                        view.Filter = delegate(object item)
                        {
                            return !((RecordItem)item).IsHoliday;
                        };
                    }
                }
            }

        }

        void GenPersonalDaysInfo()
        {
        }
    }
}
